const { Add, Update, QueryById, Query, QueryOne, Exec, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/immessage');
const logger = require('../libs/log').logger;
const encryptedData = require('../libs/common').encryptedData;
const matchhistoryAdd = require('./matchhistory').matchhistoryAdd;
var { sendMsg } = require('./wechat');
var moment = require('moment');
const {matchhistoryUpdate }= require('./matchhistory');
const sendIm = require('../libs/tencent_cloud').sendIm;

//新增
const immessageAdd = function (doc) {
  return Add('hzz_immessages', init(doc));
}

//修改
const immessageUpdate = function (doc) {
  return Update('hzz_immessages', format(doc));
}

//查询详情
const immessageInfoById = function (id) {
  return QueryById('hzz_immessages', id);
}

// 同步消息
const immessageSync = function (req) {
  try {
    let body = req.body;
    let content = body.content;
    // 校验签名
    let go_signature = req.headers['x-goeasy-signature'];
    let enData = encryptedData('sha1', content);
    if (enData == go_signature) {
      logger.info('--同步消息--immessageSync---,签名校验成功,消息入库')
      // 开始同步进数据库消息表
      insertIMmsg(content);
      return {
        "code": 200,
        "content": "success"
      }
    } else {
      logger.info('--同步消息--immessageSync---,签名校验失败')
      return {
        "code": 201,
        "content": "error"
      }
    }
  } catch (error) {
    logger.info('--同步消息--immessageSync---,error', error)
    return {
      "code": 201,
      "content": "error"
    }
  }
}
async function insertIMmsg(content) {
  logger.info('--insertIMmsg--同步聊天消息')
  let list = JSON.parse(content);
  for (const im of list) {
    let is = await QueryOne('hzz_immessages', { messageId: im.messageId });
    if (!is) {
      await immessageAdd(im);
      // 校验是否互相回复消息，互相回复消息，则创建配对记录
      await matched(im);
      // 校验是否互换联系方式，如互换联系方式，则更新配对状态
      await matchStatus(im);
      let peo = await QueryOne('hzz_peoples', { code: im.senderId }, 'nickname');
      if(!peo){
        continue;
      }
      // 发送公众号订阅消息
      // 发送提醒消息 
      logger.info('--insertIMmsg--发送公众号订阅聊天消息')
      let send_data = {
        "first": {
          "value": "您好，您的业务有新进展！",
          "color": "#173177"
        },
        "keyword1": {
          "value": "聊天消息",
          "color": "#173177"
        },
        "keyword2": {
          "value": `来自[${peo.nickname}]的消息`,
          "color": "#e8320e"
        },
        "remark": {
          "value": "点击查看并处理",
          "color": "#173177"
        }
      };
      let send_data_red = {
        "thing1": {
          "value": "聊天消息"
        },
        "thing3": {
          "value": peo.nickname
        },
        "thing4": {
          "value": `点击回复消息`
        },
        "time2": {
          "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
        }
      };
      await sendMsg('chat_tmpid', send_data, im.receiverId, "pages/message/message",send_data_red);

      await sendToInviter(im);
    }
  }
}
// 如果是条件用户，消息同步推送给推荐人
async function sendToInviter(im){
  logger.info('---sendToInviter-----',im)
  let receiverData = await QueryOne('hzz_peoples', { code: im.receiverId }, 'nickname,avator,name,name_father,isinviter,openid,invitcode');
  if(receiverData){
    let rname = receiverData.name? receiverData.name : (receiverData.name_father?receiverData.name_father:receiverData.nickname);
    if(receiverData.isinviter == 0 && !receiverData.openid && receiverData.invitcode){
      
        let senderData = await QueryOne('hzz_peoples', { code: im.senderId }, 'code,nickname,avator,name,name_father');
        let inviterData = await QueryOne('hzz_peoples', { code: receiverData.invitcode }, 'code,nickname,avator,name,name_father,grender');
        logger.info('---sendToInviter-----给条件用户推荐人发消息',inviterData)
        if(!im.payload)
        {
          return 
        }
        let message = JSON.parse(im.payload).text;
        // 给条件用户推荐人发消息
        let body={
          "appkey": "PR-6f1dea0c480f46d9a3fd1c3a706e452e",
          "senderId": im.senderId,
          "senderData": {
            "avatar": senderData.avator,
            "name": senderData.nickname +`[→${rname}]`
          },
          "to": {
              "type": "private",
              "id": receiverData.invitcode,
              "data": {
                "avatar": inviterData.avator? inviterData.avator : (inviterData.grender=='男' ? "https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png": "https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png"),
                "name": (inviterData.name ? inviterData.name : inviterData.name_father)+`[${rname}的推荐人]`
              }
          },
          "type": "text",
          "payload": message,
          "notification": {
              "title": "new message",
              "body": "你有一条新消息"
          }
        };
        logger.info('---sendToInviter-----body',body)
        await sendIm(body);
      }
  }
}
async function matched(im) {
  let rdata = await QueryOne('hzz_peoples', { code: im.receiverId }, 'isinviter');
  let sdata = await QueryOne('hzz_peoples', { code: im.senderId }, 'isinviter');
  if (rdata && sdata && rdata.isinviter != 1 && sdata.isinviter != 1) {
    let imgback = await QueryOne('hzz_immessages', { senderId: im.receiverId, receiverId: im.senderId });
    if (!!imgback) {
      logger.info('--insertIMmsg--校验是否互相回复消息，互相回复消息，则创建配对记录')
      await matchhistoryAdd({ pcode: im.receiverId, fcode: im.senderId });
    }
  }
}
async function matchStatus(im) {
  logger.info('--insertIMmsg--校验是否互换联系方式，如互换联系方式，则更新配对状态')
  let isback = await ExecGetOne(`select * from hzz_immessages WHERE messageId='${im.messageId}' AND  ((senderId='${im.senderId}' AND receiverId='${im.receiverId}') OR (senderId='${im.receiverId}' AND receiverId='${im.senderId}')) AND (payload LIKE'%我微信%' OR payload LIKE'%我的微信%' OR payload REGEXP '\([1][3456789][0-9]{9}\)')`)
  if (!!isback) {
    let ispd = await ExecGetOne(`select * from hzz_matchhistories where active<2 AND (pcode='${im.receiverId}' and matchcode='${im.senderId}') OR (pcode='${im.senderId}' and matchcode='${im.receiverId}')`);
    if (ispd) {
      logger.info('--insertIMmsg--校验是否互换联系方式，如互换联系方式，则更新配对状态')
      await matchhistoryUpdate({
        id: ispd.id,
        active: 2,
        activedes: '取得联系'
      });
    }
  }
}
async function UpdateMatchStatus(){
  console.log('--UpdateMatchStatus--校验是否互换联系方式，如互换联系方式，则更新配对状态')
  let list = await Exec(`SELECT  * from hzz_immessages
  WHERE payload LIKE'%我微信%' OR payload LIKE'%我的微信%' OR payload REGEXP '\([1][3456789][0-9]{9}\)'`);
  for (let index = 0; index < list.length; index++) {
    const im = list[index];
    let ispd = await ExecGetOne(`select * from hzz_matchhistories where active<2 AND (pcode='${im.receiverId}' and matchcode='${im.senderId}') OR (pcode='${im.senderId}' and matchcode='${im.receiverId}')`);
    if (ispd) {
      await matchhistoryUpdate({
        id: ispd.id,
        active: 2,
        activedes: '取得联系'
      });
    }
  }
}


module.exports = {
  immessageAdd,
  immessageUpdate,
  immessageInfoById,
  immessageSync,
  UpdateMatchStatus
}